package com.gack.business.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gack.business.model.Commodity;
import com.gack.business.model.CommodityCategory;
import com.gack.business.repository.CommodityCategoryRepository;
import com.gack.business.repository.CommodityRepository;
import com.gack.business.vo.CommodityVO;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.ChangeDateTimeUtil;

@Service
public class CommodityService implements CommodityServiceInterface {
	@Autowired
	private CommodityRepository commodityRepository;
	@Autowired
	private CommodityCategoryRepository categoryRepository;
	@PersistenceContext
	private EntityManager manager;
	@Autowired
	private BackLogService backLogService;
	
	@Transactional
	@Override
	public Result addCommodity(Integer faceValue, Integer salesPrice, String photoUrl, String name, String uid) {
		Result result = new Result();
		List<Commodity> commoditys = commodityRepository.findAll();
		Commodity commodity = new Commodity();
		String number=String.format("%03d",commoditys.size()+1);
		commodity.setNumber(number);
		commodity.setCategory("e4aef05a73e64411898e466454cb4216");//e4aef05a73e64411898e466454cb4216商务卡类型
		commodity.setFaceValue(faceValue);
		commodity.setSalePrice(salesPrice);
		commodity.setPhotoUrl(photoUrl);
		commodity.setName(name);
		commodity.setShelTime(new Date());
		commodity.setSalesAmount(0);
		commodity.setStatus(1);
		Commodity commodity2 = commodityRepository.save(commodity);
		result.setKey("success");
		result.setValue("添加成功");
		backLogService.addBackLog(uid, "增加一个商品，ID为" + commodity2.getId() );
		return result;
	}

	@Override
	public Result findCommodity(String id) {
		Commodity commodity = commodityRepository.findOne(id);
		
		Result result = new Result();
		if (commodity != null && commodity.getStatus() == 2) {
			result.setKey("error");
			result.setValue("查无此商品");
			return result;
		}
		/*if (commodity != null && commodity.getStatus() == 0) {
			result.setKey("error");
			result.setValue("商品已下架");
			return result;
		}
		if (commodity != null && commodity.getStatus() ==1) {
			CommodityCategory category = categoryRepository.findOne(commodity.getCategory());
			if (category != null) {
				commodity.setCategoryName(category.getName());
			}
			
			result.setKey("success");
			result.setValue(commodity);
			return result;
		}
		result.setKey("error");
		result.setValue("商品id错误");
		return result;*/
		CommodityCategory category = categoryRepository.findOne(commodity.getCategory());
		if (category != null) {
			commodity.setCategoryName(category.getName());
		}
		
		result.setKey("success");
		result.setValue(commodity);
		return result;
	}
	
	@Override
	public Map<String, Object> findCommodityList(Integer page, Integer size, Integer status, String startTime, String endTime) throws Exception {
		String jpql = "select c from Commodity c where 1=1 ";
		if (status != null) {
			jpql += "and c.status =" + status;
		}else {//and (c.status = 0 or c.status = 1)
			jpql += "and (c.status = 0 or c.status = 1)";
		}
		if (startTime != null &&! "".equals(startTime)) {
			startTime = ChangeDateTimeUtil.zExchangeUTC(startTime);
			jpql += "and c.shelTime >= '"+startTime +"'";
		}
		if (endTime != null &&! "".equals(endTime)) {
			endTime = ChangeDateTimeUtil.zExchangeUTC(endTime);
			jpql += "and c.shelTime <= '"+endTime +"'";
		}
		jpql += "order by c.number asc";
		Query query = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		List<Commodity> result = query.getResultList();
		map.put("total", result.size());
		query.setFirstResult(page * size);
		query.setMaxResults(size);
		List<Commodity> commodities = query.getResultList();
		for (Commodity commodity : commodities) {
			CommodityCategory category = categoryRepository.findOne(commodity.getCategory());
			if (category != null) {
				commodity.setCategoryName(category.getName());
			}
		}
		map.put("commodities", commodities);
		return map;
	}
	
	@Transactional
	@Override
	public Result dropOffCommodity(String id, String uid) {
		Result result = new Result();
		Commodity commodity = commodityRepository.findOne(id);
		
		if (commodity != null && commodity.getStatus() == 2) {
			result.setKey("error");
			result.setValue("查无此商品");
			return result;
		}
		if (commodity != null && commodity.getStatus() == 0) {
			result.setKey("error");
			result.setValue("商品已下架");
			return result;
		}
		
		if (commodity != null && commodity.getStatus() ==1) {
			commodityRepository.updateCommodity(0, id);
			Commodity com = commodityRepository.findOne(id);
			CommodityCategory category = categoryRepository.findOne(com.getCategory());
			if (category != null) {
				com.setCategoryName(category.getName());
			}
			result.setKey("success");
			result.setValue(com);
			backLogService.addBackLog(uid, "下架了一个商品 id为" + com.getId());
			return result;
		}

		result.setKey("error");
		result.setValue("商品id错误");
		return result;
	}
	
	@Transactional
	@Override
	public Result deleteCommodity(String id, String uid) {
		Result result = new Result();
		Commodity commodity = commodityRepository.findOne(id);
		
		if (commodity != null && commodity.getStatus() == 2) {
			result.setKey("error");
			result.setValue("查无此商品");
			return result;
		}
		
		if (commodity != null && commodity.getStatus() ==1) {
			result.setKey("error");
			result.setValue("请先下架商品");
			return result;
		}
		
		if (commodity != null && commodity.getStatus() == 0) {
			commodityRepository.updateCommodity(2,id);
			result.setKey("success");
			result.setValue("商品删除成功");
			backLogService.addBackLog(uid, "删除一个商品 id为" + id);
			return result;
		}
		
		result.setKey("error");
		result.setValue("商品id错误");
		return result;
	}

	@Override
	public Map<String, Object> findSaleList(Integer page, Integer size) {
		String jpql = "select c from Commodity c  where 1=1 ";
		jpql += "and (c.status = 0 or c.status = 1) ";
		jpql += "and c.salesAmount >0 ";
		jpql += "order by c.number asc";
		Query query = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		List<Commodity> result = query.getResultList();
		map.put("total", result.size());
		query.setFirstResult(page * size);
		query.setMaxResults(size);
		List<Commodity> commodities = query.getResultList();
		for (Commodity commodity : commodities) {
			CommodityCategory category = categoryRepository.findOne(commodity.getCategory());
			if (category != null) {
				commodity.setCategoryName(category.getName());
			}
		}
		map.put("commodities", commodities);
		return map;
	}
	@Transactional
	@Override
	public Result upshelCommodity(String id, String uid) {
		Result result = new Result();
		
		Commodity commodity = commodityRepository.findOne(id);
		
		if (commodity != null && commodity.getStatus() == 2) {
			result.setKey("error");
			result.setValue("查无此商品");
			return result;
		}
		if (commodity != null && commodity.getStatus() == 1) {
			result.setKey("error");
			result.setValue("商品已经上架");
			return result;
		}
		if (commodity != null && commodity.getStatus() == 0) {
			commodityRepository.updateCommodity(1, id);// 上架商品
			Commodity com = commodityRepository.findOne(id);
			CommodityCategory category = categoryRepository.findOne(com.getCategory());
			if (category != null) {
				com.setCategoryName(category.getName());
			}
			result.setKey("success");
			result.setValue(com);
			backLogService.addBackLog(uid, "上架了一个商品 id为" + id);
		}
		
		result.setKey("error");
		result.setValue("商品id错误");
		return result;
	}

	@Override
	public Map<String, Object> commodityList(Integer page, Integer size) {
		String jpql = "select c from Commodity c  where 1=1 ";
		jpql += "and  c.status = 1 ";
		jpql += "order by c.number asc";
		Query query = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		List<Commodity> result = query.getResultList();
		map.put("total", result.size());
		query.setFirstResult(page * size);
		query.setMaxResults(size);
		List<CommodityVO> commodityVOs = new ArrayList<>();
		List<Commodity> commodities = query.getResultList();
		for (Commodity commodity : commodities) {
			CommodityVO commodityVO =  new CommodityVO();
			BeanUtils.copyProperties(commodity, commodityVO);
			commodityVOs.add(commodityVO);
		}
		map.put("commodities", commodityVOs);
		return map;
	}

}
